package van.planifolia.worddemo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by Intellij IDEA<br>
 * 线程安全的卖票代码
 * @author Planifolia.Van
 * @version 1.0
 * @date 2022/11/1 17:53
 */
public class SafeSellTrick {
    public static void main(String[] args) {
        // 创建三个线程分别来卖票
        Sell sell = new Sell();
        new Thread(sell,"窗口A").start();
        new Thread(sell,"窗口B").start();
        new Thread(sell,"窗口C").start();

    }
}
class Sell implements Runnable{
    // 共计100张票
    private int tickNub = 100;
    private boolean flag = true;
    Lock lock = new ReentrantLock();
    @Override
    public void run() {
        while (flag){
            try {
                //进入判断之前上锁
                lock.lock();
                if (tickNub<=0){
                    flag=false;
                }else {
                    System.out.println(Thread.currentThread().getName()
                            + "卖出了一张票还剩下" + --tickNub
                            + "张");
                }
            }finally {
                // finally中解锁
                lock.unlock();
            }
        }
    }
}
